import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

//队列+宽搜_在每个树行中找最大值
//https://leetcode.cn/problems/find-largest-value-in-each-tree-row/description/
public class Test {
    public static void main(String[] args) {
        //

    }
}



//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        //
        List<Integer> res = new ArrayList<>();//用于返回结果
        if(root == null) return res;
        Queue<TreeNode> q = new LinkedList<>();//用于存放每层的节点
        q.offer(root);
        while (!q.isEmpty()){
            int size = q.size();
            int max = Integer.MIN_VALUE;//int型的最小值
            for(int i = 0; i < size; i++){
                //
                TreeNode node = q.poll();
                if(node.left != null) q.offer(node.left);
                if(node.right != null) q.offer(node.right);
                max = Math.max(max, node.val);
            }
            res.add(max);
        }
        return res;
    }
}